#include "widget.h"
#include "ui_widget.h"

#include <QSqlDatabase>
#include <QMessageBox>
#include <QSqlError>
static int id=0;
Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    //加载数据库驱动
    QSqlDatabase db=QSqlDatabase::addDatabase("QMYSQL");
    //连接配置
    db.setHostName("47.115.215.11");
    db.setDatabaseName("scott");
    db.setUserName("wmh");
    db.setPassword("336699");

    if(db.open())
    {
        QMessageBox::information(this,"连接提示","连接成功");
        Model=new QSqlTableModel;//创建模型
        Model->setTable("user");//模型与表关联
        ui->tableView->setModel(Model);//视图模型关联

    }
    else
    {
        QMessageBox::warning(this,"连接提示","连接失败");
    }

    Model->setEditStrategy(QSqlTableModel::OnManualSubmit);//设置编辑策略,点击调用submitAll，revertAll才提交
    on_btnSelect_clicked();
    id=Model->rowCount();
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_btnSelect_clicked()
{
    Model->select();
}

void Widget::on_btnAdd_clicked()
{
    int row = Model->rowCount();

    Model->insertRow(row);
    Model->setData(Model->index(row,0),++id);
    Model->setData(Model->index(row,1),180);
    Model->setData(Model->index(row,2),tr("赛罗"));
//    Model->submitAll();//提交所有未更新的修改到数据库
}

void Widget::on_btnDel_clicked()
{
    //获取选中的行
    int curRow = ui->tableView->currentIndex().row();

    //删除该行
    Model->removeRow(curRow);

    int ret = QMessageBox::warning(this, tr("删除当前行"), tr("你确定要删除该行吗"), QMessageBox::Yes | QMessageBox::No);
    if (ret == QMessageBox::Yes)
    {
        //提交到数据库
        Model->submitAll();
    }
    else
    {
        //不删除  撤销操作
        Model->revertAll();
    }
}

void Widget::on_btnRollback_clicked()
{
    Model->revertAll();
    QMessageBox::information(this,tr("TableView"),tr("撤销修改成功"));
}

void Widget::on_btnSubmit_clicked()
{
    //开启事务
    Model->database().transaction();
    if (Model->submitAll())
    {
        //提交事务
        Model->database().commit();
        QMessageBox::information(this,tr("TableView"),tr("提交修改成功"));
    }
    else
    {
        //回滚事务
        Model->database().rollback();
        QMessageBox::warning(this, tr("TableView"),tr("数据库错误: %1").arg(Model->lastError().text()));
    }

}
